package com.xidian.zhiancloud.controller.workTicket;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.dto.workTicket.ElectricTicketVODTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.workTicket.ElectricOperator;
import com.xidian.zhiancloud.model.workTicket.ElectricTicket;
import com.xidian.zhiancloud.qo.workTicket.ElectricTicketQO;
import com.xidian.zhiancloud.service.workTicket.ElectricFlowService;
import com.xidian.zhiancloud.service.workTicket.ElectricOperatorService;
import com.xidian.zhiancloud.service.workTicket.ElectricService;
import com.xidian.zhiancloud.util.zyf.RedisUtil;
import com.xidian.zhiancloud.vo.workTicket.ElectricTicketVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("Electric")
public class ElectricController extends BaseController {

    @Autowired
    private ElectricService electricService;

    @Autowired
    private ElectricFlowService electricFlowService;

    @Autowired
    private ElectricOperatorService electricOperatorService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 编辑
     *
     * @param electricTicket
     * @return 是否提交成功
     */
    @PostMapping("/addElectricTicket")
    public ResultDTO<Boolean> addFireTicket(ElectricTicket electricTicket) {
        electricTicket.setCompanyId(getSessionUserCompanyId());
        electricTicket.setApplicantId(getSessionUserid());
        electricTicket.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = true;
        // 通过是否传入id，判断是否是第一次传入（save），还是继续编辑（update）
        if (electricTicket.getId() == null) {
            res = electricService.save(electricTicket);
        } else {
            res = electricService.updateById(electricTicket);
        }
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 发布
     *
     * @param id
     * @return 是否提交成功
     */
    @PostMapping("/commitElectricTicket")
    public ResultDTO<Boolean> addElectricTicket(@RequestParam("id") Long id) {
        ElectricTicket electricTicket = electricService.getById(id);
        // 设置危险作业票id
        electricTicket.setWorkNumber(redisUtil.generateWorkId(getSessionUserCompanyId(), electricTicket.getApplicantUnitId()));
        electricTicket.setIsCommit1(1);
        // 设置导出类型
        electricTicket.setCompanyId(getSessionUserCompanyId());
        electricTicket.setCreateTime(new Date(System.currentTimeMillis()));
        electricTicket.setApplicantId(getSessionUserid());
        electricTicket.setCurrentStep(2);
        return ResultDTO.successOf(electricService.save(electricTicket), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 各单位审批（修改）
     *
     * @param electricTicket 修改对象
     * @return 是否修改成功
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    @PostMapping("/approveElectricTicket")
    public ResultDTO<Boolean> approveElectricTicket(ElectricTicket electricTicket) {
        return electricService.approveElectricTicket(electricTicket);
    }

    /**
     * 填写作业人信息，并更新所属作业票
     * @param electricOperator 作业人
     * @return 是否更新成功
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    @PostMapping("/addOperatorInfo")
    public ResultDTO<Boolean> addOperatorInfo(ElectricOperator electricOperator) {
        electricOperator.setCompanyId(getSessionUserCompanyId());
        ElectricTicket electricTicket = electricOperatorService.saveOperatorInfo(electricOperator);
        if (electricTicket == null || electricTicket.getCurrentStep() != 2){
            return ResultDTO.errorOf(-1, "不可提交作业人员信息！");
        }
        return approveElectricTicket(electricTicket);
    }

    /**
     * 删除待提交作业票*
     * @param ids 删除项id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteElectricTicket")
    public ResultDTO<Boolean> deleteElectricTicket(@RequestParam("ids") Long[] ids) {
        return ResultDTO.successOf(electricService.removeByIds(Arrays.asList(ids)), GeneralResponseEnums.SUCCESS);
    }


/**
     * 根据id查询作业票
     *
     * @param id 查询项id
     * @return 查询结构
     */

    @GetMapping("/getElectricTicket")
    public ResultDTO<ElectricTicketVODTO> getElectricTicket(@RequestParam("id") Long id) {
        if (id == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        Long companyId = getSessionUserCompanyId();
        // 返回DTO对象，为fireTicketVO及操作权限标识Map
        ElectricTicketVODTO electricTicketVODTO = electricService.getElectricTicketVODTOById(companyId, id);
        return ResultDTO.successOf(electricTicketVODTO, GeneralResponseEnums.SUCCESS);
    }


/**
     * 列表查找
     *
     * @param electricTicketQO 查询项
     * @return 查询列表
     */

    @GetMapping("getElectricTicketList")
    public ResultDTO<IPage<ElectricTicketVO>> getElectricTicketList(ElectricTicketQO electricTicketQO) {
        if (electricTicketQO.getSize() == null || electricTicketQO.getCurrent() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        electricTicketQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(electricService.getListByQO(electricTicketQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据作业票编号查询作业票id（多类型通用）
     * @param relateWorkNum 作业票编号
     * @return 作业票id
     */
    @GetMapping("/getRelateTicketByWorkNumber")
    public ResultDTO<Map<String, Long>> getRelateTicketByWorkNumber(@RequestParam("relateWorkNum") String relateWorkNum) {
        Long companyId = getSessionUserCompanyId();
        Map<String, Long> relateWorkNumberList = new HashMap<>();

        Long relateId = electricService.getRelateTicket(relateWorkNum, companyId);
        if (relateId == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.GET_FAILED);
        }
        relateWorkNumberList.put(relateWorkNum, relateId);
        return ResultDTO.successOf(relateWorkNumberList, GeneralResponseEnums.SUCCESS);
    }

    /**
     *  导出作业票
     *
     * @param request 导出请求
     * @param response 导出响应
     * @param ticketId  作业票id
     * @return 作业票doc
     * @throws Exception
     */
    @GetMapping("/export")
    public ResultDTO<Boolean> get(HttpServletRequest request, HttpServletResponse response,
                    @RequestParam("ticketId") Long ticketId) throws Exception {
        return electricService.export(request, response, ticketId);
    }



}
